<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/10/16 15:50
 * Desc:
 */
class Service_Api_Guide extends Contract_Api_Product
{
    const TYPE_ID = 106;

    public function search(array $params = array()): array
    {
        /**
         * @var $mid
         * @var $page
         * @var $pagesize
         * @var $dest_py
         * @var $price_id
         * @var $sort_type
         * @var $attr_id
         * @var $sex
         * @var $language
         * @var $keyword
         */
        extract($params);

        $offset = St_Page::offset($page, $pagesize);

        $builder = DB::select(
            'a.*',
            DB::expr('sline_m.truename as guide_name,sline_b.service_city'),
            DB::expr('(IFNULL(`sline_a`.bookcount,0)+IFNULL(`sline_member_order_statistic`.sell_num,0)) AS sell_num'))
            ->from(array('guide_service', 'a'))
            ->join(array('guide', 'b'), 'inner')
            ->on('a.guide_id', '=', DB::expr('sline_b.id'))
            ->join(array('member', 'm'), 'inner')
            ->on('b.mid', '=', DB::expr('sline_m.mid'))
            ->join('member_order_statistic', 'left')
            ->on('member_order_statistic.product_id', '=', DB::expr('`sline_a`.id'))
            ->on('member_order_statistic.type_id', '=', self::TYPE_ID);
        //按目的地搜索
        if ($dest_py && $dest_py != 'all') {
            $dest_id = Model_Destinations::get_id_by_pinyin($dest_py);
        }

        //排序
        $order_by = "";
        if (!empty($sort_type)) {
            switch ($sort_type) {
                case 1:
                    $order_by = " sline_a.price ASC,"; //价格升序
                    break;
                case 2:
                    $order_by = " sline_a.price DESC,"; //价格降序
                    break;
                case 3:
                    $order_by = " sell_num DESC,"; //销量降序
                    break;
                case 4:
                    $order_by = " sline_a.recommendnum DESC,"; //推荐
                    break;
            }
        }

        if (!empty($dest_id)) {
            $builder->join('kindorderlist', 'left')
                ->on('a.id', '=', DB::expr('`sline_kindorderlist`.aid'))
                ->on('a.webid', '=', DB::expr('`sline_kindorderlist`.webid'))
                ->on('kindorderlist.typeid', '=', self::TYPE_ID)
                ->on('kindorderlist.classid', '=', DB::expr("{$dest_id}"));
            $order_by .= "IFNULL(`sline_kindorderlist`.displayorder,9999) ASC";
        } else {
            $builder->join('allorderlist', 'left')
                ->on('a.id', '=', DB::expr('`sline_allorderlist`.aid'))
                ->on('a.webid', '=', DB::expr('`sline_allorderlist`.webid'))
                ->on('allorderlist.typeid', '=', self::TYPE_ID);
            $order_by .= "IFNULL(`sline_allorderlist`.displayorder,9999) ASC";
        }

        $now_day_time = strtotime(date('Y-m-d'));
        $builder->where('a.ishidden', '=', 0)
            ->and_where('a.status', '=', 6)
            ->and_where('a.end_time', '>=', $now_day_time);
        //属性
        if (!empty($attr_id)) {
            $attr_where = Product::get_attr_where($attr_id);
            $attr_where = str_replace('a.attrid', 'sline_a.attrid', $attr_where);
            $builder->and_where(DB::expr("{$attr_where}"));
        }
        //关键词
        if (!empty($keyword)) {
            $builder->and_where('a.title', 'like', '%' . $keyword . '%');
        }
        //擅长语言
        if (!empty($language)) {
            $builder->and_where('b.good_language', 'like', '%' . $language . '%');
        }
        // 目的地
        if (!empty($dest_id)) {
            $builder->and_where(DB::expr(" AND FIND_IN_SET('{$dest_id}',sline_a.kindlist) "));
        }
        // 性别
        if (!empty($sex) && $sex < 2) {
            $builder->and_where('m.sex', '=', $sex);
        }
        //价格区间
        if ($price_id) {
            $price_arr = DB::select()
                ->from('guide_pricelist')
                ->where('id', '=', $price_id)
                ->execute()
                ->current();
            if (!empty($price_arr)) {
                if (empty($price_arr['lowerprice'])) {
                    $builder->and_where('a.price', '<', $price_arr['highprice']);
                } elseif (empty($price_arr['highprice'])) {
                    $builder->and_where('a.price', '>', $price_arr['lowerprice']);
                } else {
                    $builder->and_where(DB::expr(" AND sline_a.price BETWEEN {$price_arr['lowerprice']} AND {$price_arr['highprice']}"));
                }
            }
        }

        $total = $builder->execute()->count();
        $list  = $builder->offset($offset)
            ->limit($pagesize)
            ->order_by(DB::expr($order_by))
            ->execute()
            ->as_array();

        $filter_keys = 'id,title,litpic,price,score,guide_name,service_city,icon_list,attr_list,bookcount,satisfyscore,service_city';
        if(!empty($list)){
            // 获取营销策略
            $marketing_strategy = Model_Api_V2_Marketing_Strategy::get_instance(self::TYPE_ID, array('mid'=> $mid));
            $uni_img = Model_Uniapp_Images::get_img_list(self::TYPE_ID);
            foreach ($list as &$v) {
                if(isset($uni_img[$v['id']])){
                    $v['litpic'] = $uni_img[$v['id']];
                }
                $v['satisfyscore'] = St_Functions::get_satisfy(self::TYPE_ID, $v['id'], $v['satisfyscore']);
                $v['score']        = St_Functions::get_satisfy(self::TYPE_ID, $v['id'], $v['satisfyscore']);
                $v['price']        = Currency_Tool::price($v['price']);
                $v['litpic']       = $this->img_url($v['litpic'], 94, 94);
                $v['icon_list']    = $this->icons($v['iconlist']);
                $v['attr_list']    = Model_Guide_Attr::get_attrname_list($v['attrid']);
                $v['bookcount']    = Model_Member_Order_statistic::get_sell_num(self::TYPE_ID, $v['id']) + intval($v['bookcount']);
                $v['satisfyscore'] = St_Functions::get_satisfy(self::TYPE_ID, $v['id'], $v['satisfyscore']);
                $v = $this->filter_data($filter_keys, $v);

                // 营销策略
                $v['marketing_strategy'] = $marketing_strategy->get_support_application($v['id']);
            }
        }

        return array(
            'total' => $total,
            'list' => $list
        );
    }

    public function info(array $params = array()): array
    {
        $id    = $params['id'];
        $guide = DB::select(DB::expr("sline_b.litpic as m_litpic,sline_b.birth_date,sline_b.qq,sline_b.wechat,sline_b.mobile,sline_a.*,sline_b.truename as title"))
            ->from(array('guide', 'a'))
            ->join(array('member', 'b'), 'inner')
            ->on('a.mid', '=', 'b.mid')
            ->where('a.id', '=', $id)
            ->where('a.status', '=', 1)
            ->execute()
            ->current();
        if (!$guide) {
            throw new Exception('没有找到该导游');
        }

        $guide['litpic']         = $this->img_url($guide['m_litpic']);
        $guide['age']            = $this->img_url($guide['birth_date']);
        $guide['guide_card_pic'] = $this->img_url($guide['guide_card_pic']);
        $guide['mobile']         = Model_Guide::complex_mobile($guide['mobile']);
        $guide['content']        = $this->content_add_domain($guide['profile']);

        unset($guide['mid'], $guide['modtime'], $guide['addtime']);
        return $guide;
    }

    public function query_condition(): array
    {

        $result = array(
            'sort' => array(
                array('id' => 0, 'name' => '综合排序'),
                array('id' => 1, 'name' => '价格从低到高'),
                array('id' => 2, 'name' => '价格从高到低'),
                array('id' => 3, 'name' => '销量最高'),
                array('id' => 4, 'name' => '产品推荐')
            ),
            'price' => array('name' => '价格', 'child' => array()),
        );

        //属性
        $result['attribute'] = Model_Api_V2_Guide::get_attribute_condition();

        //价格
        $result['price']['child'] = Model_Api_V2_Guide::get_price_condition();

        return $result;
    }

    public function create_order(array $params = array()): array
    {
        $mid        = $params['mid'];
        $product_id = $params['product_id'];
        $use_date   = $params['usedate'];
        $use_time   = strtotime($use_date);

        //出发日期
        if ($use_time < strtotime(date('Y-m-d', time()))) {
            throw new Exception('日期不正确');
        }

        $guide_service = DB::select()
            ->from('guide_service')
            ->where('id', '=', $product_id)
            ->execute()
            ->current();
        if (!isset($guide_service['id'])) {
            throw new Exception("导游服务不存在");
        }

        $service_price = DB::select()
            ->from('guide_service_price')
            ->where('service_id', '=', $product_id)
            ->and_where('day', '=', $use_time)
            ->and_where('number', '=', 1)
            ->execute()
            ->current();
        if (!isset($service_price['id'])) {
            throw new Exception("库存不足");
        }

        $order = array(
            'webid' => 0,
            'addtime' => time(),
            'typeid' => self::TYPE_ID,
            'ordersn' => St_Product::get_ordersn(self::TYPE_ID),
            'litpic' => $guide_service['litpic'],
            'productaid' => $guide_service['aid'],
            'productname' => $guide_service['title'],
            'price' => $guide_service['price'],
            'suit_name' => $guide_service['title'],
            'paytype' => $guide_service['paytype'],
            'dingjin' => 0,
            'childprice' => 0,
            'childnum' => 0,
            'oldprice' => 0,
            'oldnum' => 0,
            'need_confirm' => 0,
            'auto_close_time' => 0,
            'productautoid' => $product_id,
            'dingnum' => 1,
            'suitid' => 0,
            'source' => $params['source'],
            'usedate' => $params['usedate'],
            'linkman' => $params['linkman'],
            'linktel' => $params['linktel'],
            'linkemail' => empty($params['linkemail']) ? '' : $params['linkemail'],
            'remark' => !empty($params['remark']) ? $params['remark'] : '',
            'memberid' => $mid,
            'jifenbook' => $guide_service['jifenbook_id'],
            'jifencomment' => ($comment = Model_Jifen::get_used_jifencomment(self::TYPE_ID)) ? 0 : $comment['value'],
        );

        // 处理优惠券
        $coupon_id = Arr::get($params, 'coupon_id', 0);
        if ($coupon_id) {
            $coupon_check = Model_Api_V2_Coupon::order_use_coupon_check($coupon_id, $mid, $order);
        }

        //写入订单
        $result = Model_Api_V2_Order::add_order($order, 'Model_Guide');
        if (!$result['status']) {
            throw new Exception($result['msg']);
        }

        $order_info = Model_Member_Order::order_info($order['ordersn']);

        // 添加优惠券使用
        if(!empty($coupon_check)){
            Model_Coupon::add_coupon_order($coupon_check['cid'], $order['ordersn'], $coupon_check['order_total_price'], $coupon_check, $coupon_id);
        }

        //红包
        $envelope_member_id = Arr::get($params, 'envelope_member_id', 0);
        if ($envelope_member_id) {
            if (St_Functions::is_normal_app_install('red_envelope')) {
                Model_Order_Envelope::order_use_envelope($envelope_member_id, $order['ordersn'], self::TYPE_ID, $mid);
            }
        }

        //写导游订单表
        $guide_order = array(
            'ordersn' => $order['ordersn'],
            'guide_id' => $guide_service['guide_id'],
            'people_num' => $guide_service['service_number'],
            'award' => Model_Guide::get_award($order['ordersn'], $order_info['pay_price'])
        );
        list($id, $flag) = DB::insert('guide_order', array_keys($guide_order))->values(array_values($guide_order))->execute();

        //订单结算信息表数据更新
        Model_Member_Order_Compute::update($order['ordersn']);

        // 预订事件
        Hook::trigger('order_created', $order_info);

        $filter_keys = array('id', 'orderid', 'ordersn', 'pageType', 'typeid', 'status');
        return $this->filter_data($filter_keys, $order_info);
    }

    use Trait_Api_Guide;
}